import {defineStore} from 'pinia';
import $event from "@util/event.ts";

// 日志前缀
const logPr = "【WS-森林火情】";

export const useWsSlhq = defineStore('wsSlhq', {
    state: () => ({
        ws: null as WebSocket | null,
        heartTimer: null as NodeJS.Timeout | null,
        reconnectTimer: null as NodeJS.Timeout | null,
        isManualClose: false, // 是否手动关闭连接
        reconnectAttempts: 0, // 重连尝试次数
        maxReconnectAttempts: 5, // 最大重连次数
        reconnectInterval: 3000, // 初始重连间隔
        isAlive: true, // 心跳状态检测
        aliveCheckTime: 10000,//心跳检查
        aliveTimeout: 5000,//心跳超时
    }),
    actions: {
        //消息处理函数 ✅
        handleMessage(res: any) {
            if (res.id) {
                console.log(logPr + "消息处理：通知森林火情，新增数据")
                $event.emit("slhqWs", res)
            }
        },

        // 初始化连接
        connect(url: string) {
            // 清理旧连接和定时器
            this.clearTimers();
            this.isManualClose = false;

            console.log(logPr + "连接地址：" + url)
            this.ws = new WebSocket(url);

            this.ws.onopen = () => {
                console.log(logPr + "连接成功");
                this.reconnectAttempts = 0; // 连接成功重置重连计数
                let param = {
                    "userid": "604548977299525",
                    "roleid": "ROLE_ADMIN",
                    "messagetype": "fire"
                }
                this.ws.send(param);

                // this.startHeartBeat(); // 开启心跳检测[8](@ref)
            };

            this.ws.onmessage = (event: any) => {
                console.log(logPr + '消息处理 接收消息===>', event.data);

                // 收到任何消息都重置心跳状态
                this.isAlive = true;

                // 空消息
                if (!event.data) {
                    return;
                }

                try {
                    const msg = JSON.parse(event.data);

                    // 处理心跳响应
                    if (msg.type == 'pong') {
                        console.log(logPr + '收到心跳响应');
                        return;
                    }

                    this.handleMessage(msg);

                } catch (e) {
                    console.log(logPr + '消息解析错误', e);
                }
            };

            this.ws.onclose = (e) => {
                console.log(logPr + '连接关闭');
                console.log(logPr + '错误码:', e.code, '原因:', e.reason, '是否正常关闭:', e.wasClean);

                // 非手动关闭时尝试重连
                if (!this.isManualClose) {
                    this.handleReconnect(url);
                }
            };

            this.ws.onerror = (error) => {
                console.log(logPr + '错误信息 ', error);
                if (!this.isManualClose) {
                    this.handleReconnect(url);
                }
            };
        },

        // 心跳检测机制优化
        startHeartBeat() {
            this.stopHeartBeat(); // 先停止旧的心跳
            this.isAlive = true; // 重置状态

            // 主心跳定时器
            this.heartTimer = setInterval(() => {
                if (this.ws?.readyState === WebSocket.OPEN) {
                    let param = JSON.stringify({type: "ping"})
                    // console.log(logPr + '心跳===>发起心跳检测', param);

                    // 发送心跳包
                    this.ws.send(param);

                    // 心跳响应检测定时器
                    setTimeout(() => {
                        if (!this.isAlive) {
                            console.log(logPr + '心跳响应超时，主动断开连接');
                            this.ws?.close();
                        } else {
                            this.isAlive = false; // 重置状态等待下次响应
                        }
                    }, this.aliveTimeout);
                }
            }, this.aliveCheckTime);

        },

        // 智能重连机制
        handleReconnect(url: string) {
            if (this.reconnectAttempts >= this.maxReconnectAttempts) {
                console.log(logPr + `已达到最大重连次数(${this.maxReconnectAttempts})，停止重连`);
                return;
            }

            // 清除旧的重连定时器防止加速
            if (this.reconnectTimer) {
                clearTimeout(this.reconnectTimer);
                this.reconnectTimer = null;
            }

            // 指数退避算法
            const delay = this.reconnectInterval * Math.pow(2, this.reconnectAttempts);
            console.log(logPr + `第${this.reconnectAttempts + 1}次重连，等待${delay}ms`);

            this.reconnectTimer = setTimeout(() => {
                console.log(logPr + `重连`);
                this.reconnectAttempts++;
                this.connect(url);
            }, delay);
        },

        // 手动关闭连接
        closeConnection() {
            this.isManualClose = true;
            this.clearTimers();
            this.ws?.close(1000, logPr + '用户主动关闭');
        },

        // 清理所有定时器
        clearTimers() {
            if (this.heartTimer) {
                clearInterval(this.heartTimer);
                this.heartTimer = null;
            }
            if (this.reconnectTimer) {
                clearTimeout(this.reconnectTimer);
                this.reconnectTimer = null;
            }
            console.log(logPr + `定时器---清理所有定时器`);

        },

        // 停止心跳检测
        stopHeartBeat() {
            if (this.heartTimer) {
                clearInterval(this.heartTimer);
                this.heartTimer = null;
                console.log(logPr + '心跳===>停止检测');
            }
        }
    }
});